package com.easy.component.network.interceptor;


import com.easy.component.network.utils.NetWorkLogger;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 描述: {打印log拦截器}
 * 作者:jack-song
 * 创建日期: 2017/9/11 19:51
 * 修改日期: 2017/9/11
 * 版本: {1.0}
 */
public class LoggingInterceptor implements Interceptor {
    private static final String TAG = LoggingInterceptor.class.getName();

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        logcatRequest(request);
        long startNs = System.nanoTime();
        Response response;
        try {
            response = chain.proceed(request);
        } catch (Exception e) {
            NetWorkLogger.e(TAG, "---返回日志异常--->" + e.getMessage());
            throw e;
        }
        long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

        return logcatResponse(response, tookMs);
    }

    /**
     * 打印请求url 方法 参数 header
     *
     * @param request
     */
    private void logcatRequest(Request request) {
        try {
            String url = request.url().url() + "";
            NetWorkLogger.d(TAG, "---url--->" + url);
            String method = request.method();
            NetWorkLogger.d(TAG, "---method--->" + method);

            StringBuffer headerBuffer = new StringBuffer();
            Headers headers = request.headers();
            if (null != headers && headers.size() > 0) {
                for (int i = 0; i < headers.size(); i++) {
                    headerBuffer.append("requestHeader-->").append(headers.name(i) + ": " + headers.value(i));
                }
            }
            NetWorkLogger.d(TAG, "---requestHeaders--->" + headerBuffer.toString());
            String body = request.body().toString();
            NetWorkLogger.d(TAG, "---requestBody--->" + body);
        } catch (Exception e) {
            NetWorkLogger.e(TAG, "---请求日志异常--->" + e.getMessage());
        }
    }

    /**
     * 打印返回值
     *
     * @param response
     * @param when
     */
    private Response logcatResponse(Response response, long when) {
        try {
            NetWorkLogger.d(TAG, "---when--->" + when);
            StringBuffer headerBuffer = new StringBuffer();
            Headers headers = response.headers();
            if (null != headers && headers.size() > 0) {
                for (int i = 0; i < headers.size(); i++) {
                    headerBuffer.append("responseHeader-->").append(headers.name(i) + ": " + headers.value(i));
                }
            }
            String body = response.body().toString();
            NetWorkLogger.d(TAG, "---responseBody--->" + body);
        } catch (Exception e) {
            NetWorkLogger.e(TAG, "---返回日志异常--->" + e.getMessage());
        }
        return response;
    }
}
